import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';

// services
import { ConstantService } from '../../../../core/services/constant.service';
import { ServerService } from '../../../../core/services/server.service';
import { StorageService } from '../../../../core/services/storage.service';

@Component({
    selector: 'app-main',
    templateUrl: './main.component.html',
    styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit {
    isCollapsed = false; // 侧边菜单栏默认打开
    menus: object[]; // 菜单列表
    loginUser: object; // 当前登录用户
    selectedSubMenu: string; // 被选中的sub-menu
    constructor(
        private constant: ConstantService,
        private server: ServerService,
        private storage: StorageService,
        private router: Router,
        private message: NzMessageService
    ) {
        this.menus = this.storage.getItem(this.constant.storage.menus);
        this.loginUser = this.storage.getItem(this.constant.storage.currentUser);
    }

    ngOnInit() {
        console.log(location.pathname);
        // 默认打开被选中菜单的sub-menu
        const paths = location.pathname.split('/');
        if (paths.length > 1) {
            this.selectedSubMenu = '/' + paths[2];
        }
    }

    /**
     * 退出登录
     * 清空本地缓存
     * 清空redis缓存
     * 更新用户信息
     * @param id 
     */
    async logout(id): Promise<void> {
        const token = this.storage.getItem(this.constant.storage.token);
        if (token) {
            const param = {
                token,
                id
            };
            const result = await this.server.fetch(this.constant.api.login.logout, param);
            if (result) {
                this.message.success('您已成功退出登录');
                this.storage.removeItem(this.constant.storage.token);
                this.storage.removeItem(this.constant.storage.currentUser);
                this.router.navigate(['/login']);
            } else {
                this.message.error('抱歉,退出登录失败');
            }
        } else {
            this.message.info('您已退出登录!');
            this.router.navigate(['/login']);
        }
    }

}
